package com.wwdx.controller.rest;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.wwdx.controller.base.BaseController;
import com.wwdx.model.WwdxBookModel;
import com.wwdx.model.WwdxThemeModel;
import com.wwdx.model.WwdxVipProductModel;
import com.wwdx.model.dto.BookBusinessDTO;
import com.wwdx.model.dto.ResultBean;
import com.wwdx.utils.ConstantHolder;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;

/**
 * @author liguoliang
 * @date 2018/5/24 10:05
 */
@RestController
@RequestMapping("/product")
@Api(tags = "产品接口")
public class RestProductController extends BaseController{

    /**
     * 主题包列表
     * @param type {@link WwdxThemeModel#type}
     */
    @RequestMapping("/theme/list/{token}/{sign}/{timestamp}/{merchantId}/{type}/{page}/{rows}")
    @ApiOperation(value = "主题包列表",httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "令牌",required = true),
            @ApiImplicitParam(name = "sign",value = "签名",required = true),
            @ApiImplicitParam(name = "timestamp",value = "时间戳",required = true),
            @ApiImplicitParam(name = "merchantId",value = "商户ID",required = true),
            @ApiImplicitParam(name = "page",value = "分页参数",required = true,defaultValue = "1"),
            @ApiImplicitParam(name = "rows",value = "分页参数",required = true,defaultValue = "10"),
            @ApiImplicitParam(name = "type",value = "主题包类型：0主题包1书单列表",required = true,defaultValue = "0")
    })
    public ResultBean themelist(@PathVariable("token") String token, @PathVariable("sign") String sign,
                                @PathVariable("merchantId") String merchantId,@PathVariable("timestamp") String timestamp,
                                @PathVariable("type") Integer type, @PathVariable("page") Integer page, @PathVariable("rows") Integer rows){

        SortedMap<String, Object> sortedMap = super.getSortedMap(token,timestamp);
        sortedMap.put("page",page);
        sortedMap.put("rows",rows);
        sortedMap.put("type",type);
        sortedMap.put("merchantId",merchantId);
        ResultBean resultBean = super.validSignResult(sign,sortedMap);
        if (resultBean.getStatus() == 1){
            return resultBean;
        }
        String openId = wwdxWeixinUserService.getByToken(token);
        WwdxThemeModel model = WwdxThemeModel.builder().status(0).type(type).build();
        Map<String,Object> map = Maps.newHashMapWithExpectedSize(2);
        map.put("count",wwdxThemeService.selectModelCount(model));
        map.put("list",productService.themeList(wwdxThemeService.selectModelList(model,page,rows),openId,merchantId));
        return renderSuccess(map);
    }

    /**
     * 主题包详情
     */
    @RequestMapping("/theme/detail/{token}/{sign}/{timestamp}/{themeid}/{merchantId}")
    @ApiOperation(value = "主题包详情",httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "令牌",required = true),
            @ApiImplicitParam(name = "sign",value = "签名",required = true),
            @ApiImplicitParam(name = "timestamp",value = "时间戳",required = true),
            @ApiImplicitParam(name = "themeid",value = "主题包ID",required = true)
    })
    public ResultBean themedetail(@PathVariable("token") String token, @PathVariable("sign") String sign,
                                  @PathVariable("themeid") Long themeid, @PathVariable("timestamp") String timestamp,
                                  @PathVariable("merchantId") String merchantId) {

        logger.info("主题包详情:{}",themeid);
        SortedMap<String, Object> sortedMap = super.getSortedMap(token,timestamp);
        sortedMap.put("themeid", themeid);
        sortedMap.put("merchantId", merchantId);
        ResultBean resultBean = super.validSignResult(sign,sortedMap);
        if (resultBean.getStatus() == 1){
            return resultBean;
        }
        String openId = wwdxWeixinUserService.getByToken(token);
        zSetOperations.incrementScore(ConstantHolder.THEME_SCORE_LIST, themeid.toString(), RandomUtils.nextInt(1, 4));
        return renderSuccess(productService.themeDetail(wwdxThemeService.getByThemeId(themeid), openId,merchantId));
    }

    /**
     * 书籍列表
     * @param type {@link WwdxBookModel#type}
     */
    @RequestMapping("/book/list/{token}/{sign}/{timestamp}/{merchantId}/{type}/{sortType}/{page}/{rows}")
    @ApiOperation(value = "书籍列表",httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "令牌",required = true),
            @ApiImplicitParam(name = "sign",value = "签名",required = true),
            @ApiImplicitParam(name = "timestamp",value = "时间戳",required = true),
            @ApiImplicitParam(name = "merchantId",value = "商户ID",required = true),
            @ApiImplicitParam(name = "type",value = "书籍类型：0 书籍 1 小课",required = true,defaultValue = "0"),
            @ApiImplicitParam(name = "sortType",value = "排序类型：2 最热，默认为最新",defaultValue = "1"),
            @ApiImplicitParam(name = "page",value = "分页参数",required = true,defaultValue = "1"),
            @ApiImplicitParam(name = "rows",value = "分页参数",required = true,defaultValue = "10")
    })
    public ResultBean booklist(@PathVariable("token") String token, @PathVariable("sign") String sign,
                               @PathVariable("type") Integer type, @PathVariable("sortType") Integer sortType,
                               @PathVariable("page") Integer page, @PathVariable("rows") Integer rows,
                               @PathVariable("timestamp") String timestamp,@PathVariable("merchantId") String merchantId) {

        SortedMap<String, Object> sortedMap = super.getSortedMap(token,timestamp);
        sortedMap.put("type", type);
        sortedMap.put("page", page);
        sortedMap.put("rows", rows);
        sortedMap.put("merchantId", merchantId);
        ResultBean resultBean = super.validSignResult(sign,sortedMap);
        if (resultBean.getStatus() == 1){
            return resultBean;
        }
        String openId = wwdxWeixinUserService.getByToken(token);
        WwdxBookModel wwdxBookModel = WwdxBookModel.builder().type(type).status(0).build();
        List<BookBusinessDTO.BookListDTO> bookListDTOS;
        long count;
        //点击量最高排序情况
        int i = 2;
        if (type == 0 && sortType == i){
            Page redisPages = super.getRedisPages(page, rows);
            Set<Object> bookids = zSetOperations.reverseRange(ConstantHolder.BOOK_SCORE_LIST, redisPages.getPage(), redisPages.getRows());
            List<WwdxBookModel> list = Lists.newArrayListWithExpectedSize(bookids.size());
            bookids.forEach(bookid-> list.add(wwdxBookService.getByBookId(Long.valueOf(bookid.toString()))));
            bookListDTOS = productService.bookList(list, openId,merchantId);
            count = zSetOperations.range(ConstantHolder.BOOK_SCORE_LIST,0,-1).size();
        }else {
            bookListDTOS = productService.bookList(wwdxBookModel, openId,merchantId, page, rows);
            count = wwdxBookService.selectModelCount(wwdxBookModel);
        }
        Map<String, Object> map = Maps.newHashMapWithExpectedSize(2);
        map.put("book_list", bookListDTOS);
        map.put("count",count);
        return renderSuccess(map);
    }

    /**
     * 书籍详情
     */
    @RequestMapping("/book/detail/{token}/{sign}/{timestamp}/{bookid}/{merchantId}")
    @ApiOperation(value = "书籍详情",httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "令牌",required = true),
            @ApiImplicitParam(name = "sign",value = "签名",required = true),
            @ApiImplicitParam(name = "timestamp",value = "时间戳",required = true),
            @ApiImplicitParam(name = "bookid",value = "书籍ID",required = true),
            @ApiImplicitParam(name = "merchantId",value = "商户ID",required = true)
    })
    public ResultBean bookdetail(@PathVariable("token") String token, @PathVariable("sign") String sign,
                                 @PathVariable("bookid") Long bookid, @PathVariable("timestamp") String timestamp,
                                 @PathVariable("merchantId") String merchantId){

        logger.info("书籍详情:{}",bookid);
        SortedMap<String, Object> sortedMap = super.getSortedMap(token,timestamp);
        sortedMap.put("bookid",bookid);
        sortedMap.put("merchantId",merchantId);
        ResultBean resultBean = super.validSignResult(sign,sortedMap);
        if (resultBean.getStatus() == 1){
            return resultBean;
        }
        String openId = wwdxWeixinUserService.getByToken(token);
        //书籍才有最热
        WwdxBookModel wwdxBookModel = wwdxBookService.getByBookId(bookid);
        if (wwdxBookModel != null && wwdxBookModel.getType() == 0){
            zSetOperations.incrementScore(ConstantHolder.BOOK_SCORE_LIST, bookid.toString(), RandomUtils.nextInt(1, 4));
        }
        return renderSuccess(productService.bookDetail(bookid, openId,merchantId));
    }

    /**
     * 书籍下章节列表
     * @param bookid 书籍ID
     */
    @RequestMapping("/bookchapter/list/{token}/{sign}/{timestamp}/{bookid}/{merchantId}")
    @ApiOperation(value = "书籍下章节列表",httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "令牌",required = true),
            @ApiImplicitParam(name = "sign",value = "签名",required = true),
            @ApiImplicitParam(name = "timestamp",value = "时间戳",required = true),
            @ApiImplicitParam(name = "merchantId",value = "商户ID",required = true),
            @ApiImplicitParam(name = "bookid",value = "书籍ID",required = true)
    })
    public ResultBean bookchapterlist(@PathVariable("token") String token, @PathVariable("sign") String sign,
                                      @PathVariable("bookid") Long bookid, @PathVariable("timestamp") String timestamp,
                                      @PathVariable("merchantId") String merchantId){

        SortedMap<String, Object> sortedMap = super.getSortedMap(token, timestamp);
        sortedMap.put("bookid",bookid);
        sortedMap.put("merchantId",merchantId);
        ResultBean resultBean = super.validSignTokenResult(sign,sortedMap);
        if (resultBean.getStatus() == 1){
            return resultBean;
        }
        String openId = (String) resultBean.getData();
        return renderSuccess(wwdxBookChapterService.findBookChapterList(bookid,openId,merchantId));
    }

    /**
     * 首页热搜
     */
    @RequestMapping("/book/hotsearch")
    @ApiOperation(value = "首页热搜",httpMethod = "GET")
    public ResultBean bookhotsearch(){
        WwdxBookModel wwdxBookModel = WwdxBookModel.builder().status(0).type(0).random(true).build();
        List<WwdxBookModel> wwdxBookModels = wwdxBookService.selectModelList(wwdxBookModel, 1, 12);
        List<BookBusinessDTO> list = Lists.newArrayListWithExpectedSize(wwdxBookModels.size());
        wwdxBookModels.forEach(bookModel -> {
            BookBusinessDTO dto = new BookBusinessDTO();
            BeanUtils.copyProperties(bookModel,dto);
            list.add(dto);
        });
        return renderSuccess(list);
    }

    /**
     * 首页书籍搜索
     * @param word 搜索关键字
     */
    @RequestMapping("/book/search")
    @ApiOperation(value = "首页书籍搜索",httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "令牌",required = true),
            @ApiImplicitParam(name = "sign",value = "签名",required = true),
            @ApiImplicitParam(name = "timestamp",value = "时间戳",required = true),
            @ApiImplicitParam(name = "merchantId",value = "商户ID",required = true),
            @ApiImplicitParam(name = "word",value = "搜索关键字",required = true),
            @ApiImplicitParam(name = "page",value = "分页参数",required = true,defaultValue = "1"),
            @ApiImplicitParam(name = "rows",value = "分页参数",required = true,defaultValue = "10")
    })
    public ResultBean booksearch(String token, String sign, String word, String timestamp,
                                 String merchantId,Integer page, Integer rows)  {
        logger.info("书籍或书籍作者搜索:{}",word);
        SortedMap<String, Object> sortedMap = super.getSortedMap(token,timestamp);
        ResultBean resultBean = super.validSignResult(sign,sortedMap);
        if (resultBean.getStatus() == 1){
            return resultBean;
        }
        String openId = wwdxWeixinUserService.getByToken(token);
        WwdxBookModel model = WwdxBookModel.builder().status(0).type(0).word(word).build();
        return renderSuccess(productService.bookList(wwdxBookService.selectModelList(model,page,rows),openId,merchantId));
    }

    /**
     * VIP产品列表
     */
    @RequestMapping("/vip/list")
    @ApiOperation(value = "VIP产品列表",httpMethod = "GET")
    public ResultBean viplist(){
        WwdxVipProductModel model = WwdxVipProductModel.builder().status(1).build();
        return renderSuccess(wwdxVipProductService.selectModelList(model, 1, 10));
    }


    /**
     * 用户VIP信息
     * @param openId 用户业务ID
     */
    @RequestMapping("/vip/get")
    @ApiOperation(value = "用户VIP信息",httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "openId",value = "用户业务ID",required = true)
    })
    public ResultBean vipget(String openId){
        return renderSuccess(wwdxVipUserService.getByOpenId(openId));
    }

    /**
     * 撰稿人信息
     * @param userid 撰稿人或音频转述师ID
     * @param page 分页参数
     * @param rows 分页参数
     */
    @RequestMapping("/copywriter/{token}/{sign}/{timestamp}/{merchantId}/{userid}/{page}/{rows}")
    @ApiOperation(value = "撰稿人或音频转述师信息",httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "令牌",required = true),
            @ApiImplicitParam(name = "sign",value = "签名",required = true),
            @ApiImplicitParam(name = "timestamp",value = "时间戳",required = true),
            @ApiImplicitParam(name = "merchantId",value = "商户ID",required = true),
            @ApiImplicitParam(name = "userid",value = "撰稿人或音频转述师ID",required = true),
            @ApiImplicitParam(name = "page",value = "分页参数",required = true,defaultValue = "1"),
            @ApiImplicitParam(name = "rows",value = "分页参数",required = true,defaultValue = "10")
    })
    public ResultBean copywriter(@PathVariable("token") String token, @PathVariable("sign") String sign,
                                 @PathVariable("userid") Long userid, @PathVariable("timestamp") String timestamp,
                                 @PathVariable("merchantId") String merchantId,
                                 @PathVariable("page") Integer page, @PathVariable("rows") Integer rows){

        SortedMap<String, Object> sortedMap = super.getSortedMap(token,timestamp);
        sortedMap.put("userid",userid);
        sortedMap.put("merchantId",merchantId);
        sortedMap.put("page",page);
        sortedMap.put("rows",rows);
        ResultBean resultBean = super.validSignResult(sign,sortedMap);
        if (resultBean.getStatus() == 1){
            return resultBean;
        }
        String openId = wwdxWeixinUserService.getByToken(token);
        return renderSuccess(wwdxCopywriterService.getCopyWriter(openId,merchantId,userid,page,rows));
    }
}